package io.renren.modules.sjdriverapply.controller;

import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.modules.driver.entity.SjDriverEntity;
import io.renren.modules.driver.service.SjDriverService;
import io.renren.modules.sjdriverapply.entity.SjDriverApplyEntity;
import io.renren.modules.sjdriverapply.service.SjDriverApplyService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 
 * 
 * @author zhangheng
 * @email zh_123shmily@163.com
 * @date 2018-05-05 16:20:37
 */
@RestController
@RequestMapping("sjdriverapply")
public class SjDriverApplyController {
	@Autowired
	private SjDriverApplyService sjDriverApplyService;

	@Autowired
	private SjDriverService sjDriverService;

	@Value("${qwj.backManageDriverInfoPath}")
	String ROOT_DriverInfoImg;

	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sjdriverapply:list")
	public R list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);

		List<SjDriverApplyEntity> sjDriverApplyList = sjDriverApplyService.queryList(query);
		int total = sjDriverApplyService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(sjDriverApplyList, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}
	
	
	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("sjdriverapply:info")
	public R info(@PathVariable("id") Long id){
		SjDriverApplyEntity sjDriverApply = sjDriverApplyService.queryObject(id);
		
		return R.ok().put("sjDriverApply", sjDriverApply);
	}
	
	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("sjdriverapply:save")
	public R save(@RequestBody SjDriverApplyEntity sjDriverApply){
		sjDriverApply.setIfExamine(0);
		sjDriverApplyService.save(sjDriverApply);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("sjdriverapply:update")
	public R update(@RequestBody SjDriverApplyEntity sjDriverApply){
		sjDriverApplyService.update(sjDriverApply);
		return R.ok();
	}

	/**
	 * 司机信息通过审核
	 */
	@RequestMapping("/check")
	@RequiresPermissions("sjdriverapply:check")
	@Transactional
	public R check(@RequestBody SjDriverApplyEntity sjDriverApply){
		//修改司机申请表
		sjDriverApply.setIfExamine(1);
		sjDriverApplyService.update(sjDriverApply);
		//插入司机表
		String mobile = sjDriverApply.getMobile();
		SjDriverEntity driver = sjDriverService.queryObjectByUserName(mobile);
        if(driver == null){
			SjDriverEntity newDriver = new SjDriverEntity();
            newDriver.setDriverApplyId(sjDriverApply.getId());
            newDriver.setUsername(sjDriverApply.getMobile());
            newDriver.setMobile(sjDriverApply.getMobile());
            newDriver.setSex(sjDriverApply.getSex());
            newDriver.setRealname(sjDriverApply.getName());
            newDriver.setAge(sjDriverApply.getAge());
            newDriver.setIdCard(sjDriverApply.getIdCard());
            newDriver.setDriveStatus("0");
            newDriver.setCarstyle(sjDriverApply.getCarstyle());
            newDriver.setCarno(sjDriverApply.getCarno());
            newDriver.setCreateTime(new Date());
            newDriver.setStatus(1l);
            newDriver.setBankCardNo(sjDriverApply.getBankCardNo());
            sjDriverService.save(newDriver);
		}else{
        	return R.error(1,"该司机已经存在！");
		}
		return R.ok().put("msg","司机审核成功！");
	}

	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("sjdriverapply:delete")
	public R delete(@RequestBody Long[] ids){
		sjDriverApplyService.deleteBatch(ids);
		
		return R.ok();
	}

	/**
	 * 上传身份证照片
	 *
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadCard", method = RequestMethod.POST, headers = {"Content-Type=multipart/form-data"})
	public R uploadCard(@RequestBody MultipartFile file, HttpServletRequest request) {

		String filePath = "";
		String filename = "";
		// 判断文件是否为空
		if (!file.isEmpty()) {
			if (file.getSize() > 10240000) {
				throw new RRException("上传失败：文件大小不能超过10M");
			}
			try {
				//提取后缀
				String postfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

				// 文件命名
				filename = DateUtils.format(new Date(), "yyyyMMddHHmmss") + RandomUtils.generateString(5)+ postfix;
				filePath = ROOT_DriverInfoImg + filename;
				File saveDir = new File(filePath);

				//判断目标文件所在的目录是否存在
				if (!saveDir.getParentFile().exists()) {
					//如果目标文件所在的目录不存在，则创建父目录
					saveDir.getParentFile().mkdirs();
				}
				// 转存文件
				file.transferTo(saveDir);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			throw new RRException("上传失败:请添加上传文件！");
		}

		return R.ok().put("url", filename);//返回图片的名字

	}
	
}
